package cn.wolfcode.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class OSSUploadUtils {
    /**
     * 上传文件
     */
    @Autowired
    private OSSConfig ossConfig;
    /*@Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;*/

    public String upload(MultipartFile file) throws IOException {
        //获取上传文件的流
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        // 用 uuid 生成随机名 拼接 后缀
        String fileName = UUID.randomUUID().toString() +
                originalFilename.substring(originalFilename.lastIndexOf("."));
        //避免文件覆盖

        //上传 获取连接对象
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret());
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), fileName, inputStream);
        ossClient.putObject(putObjectRequest);
        /**
         *
         *endpoint      https://oss-cn-beijing.aliyuncs.com
         * bucketName = "java61--oss" + .
         *
         *              https://java61--oss.oss-cn-beijing.aliyuncs.com/fileName
         */
        StringBuilder stringBuilder = new StringBuilder(ossConfig.getEndpoint());
        stringBuilder.insert(ossConfig.getEndpoint().indexOf("oss"), ossConfig.getBucketName() + ".");
        stringBuilder.append("/");
        stringBuilder.append(fileName);
        return stringBuilder.toString();

    }
}
